package serviceimpl;

import dao.DetailDao;
import daoimpl.DetailDaoImpl;
import javabean.Detail;
import service.UserModuleService;
import dao.UserDao;
import daoimpl.UserDaoImpl;
import javabean.User;

import java.util.ArrayList;


public class UserModuleServiceImpl implements UserModuleService {
    private final UserDao<User> userDao = new UserDaoImpl();
    private final DetailDao<Detail> detailDao = new DetailDaoImpl();

    @Override
    public boolean userResetPassword(int uid, String password) {
        int i = userDao.updatePasswordById(uid, password);
        return i == 1;
    }

    @Override
    public User findMySelf(int id) {
        ArrayList<User> users = userDao.selectById(id);
        if (!users.isEmpty()) {
            return users.get(0);
        }
        return null;
    }

    @Override
    public boolean deposit(int id, double money) {
        int i = userDao.updateAddBalanceById(id, money);
        //根据id获取账号 用于日志添加
        String username = findMySelf(id).getUserName();
        Detail detail = new Detail(username, username, money);
        int insert = detailDao.insert(detail);
        return i == insert && i == 1;
    }

    @Override
    public boolean withdrawal(int id, double money) {
        int i = userDao.updateSubBalanceById(id, money);
        //根据id获取账号 用于日志添加
        String username = findMySelf(id).getUserName();
        Detail detail = new Detail(username, username, money * -1);
        int insert = detailDao.insert(detail);
        return i == insert && i == 1;
    }

    @Override
    public int transfer(String myUserName, String toUserName, double money) {
        ArrayList<User> users = userDao.selectByUserName(myUserName);
        User toUser = null;
        User myUser = null;
        if(!users.isEmpty()) {
            myUser = users.get(0);
        }
        users = userDao.selectByUserName(toUserName);
        if(!users.isEmpty()) {
            toUser = users.get(0);
        }
        if(toUser != null && myUser != null && myUser.getBalance() >= money) {
            Detail detail = new Detail(myUserName, toUserName, money);
            int trans = userDao.updateBalanceByMyIdAndToId(myUser.getId(), toUser.getId(), money);
            if(trans == 1) {
                detailDao.insert(detail);
                return 1;
            }
            return 0;
        }
        return -1;
    }

    @Override
    public ArrayList<Detail> findMyDetail(String username) {
        return detailDao.selectByMyUsername(username);
    }
}